package com.bawei.day18_mediaplayer2;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bawei.day18_mediaplayer2.adapter.SongAdapter;
import com.bawei.day18_mediaplayer2.bean.SongBean;
import com.bawei.day18_mediaplayer2.service.MusicService;
import com.bawei.day18_mediaplayer2.utils.NetUtils;
import com.bawei.day18_mediaplayer2.utils.SongsUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/***
  1.使用内容提供者获得所有的音乐并展示列表
  2.使用服务管理音乐：一堆方法
  3.前台服务通知栏

 本页面：
 弹出窗体：
 通知栏：





 */
public class MainActivity extends AppCompatActivity {

    private static final String TAG = "ytx";
    private ImageView imageView,iv_pre,iv_paly,iv_next;
    private RelativeLayout relativeLayout;
    private SeekBar seekBar;
    private TextView tv_duration,tv_current;
    private TextView textView;
    private ListView listView;
    private SongAdapter songAdapter;
    private List<SongBean> songBeans;
    private MusicService.MusicBinder musicBinder;
    private Timer timer;
    private MusicRecevicer musicRecevicer;
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            musicBinder = (MusicService.MusicBinder) service;
            musicBinder.setList(songBeans);//为服务中设置音乐集合




        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            requestPermissions(new String[]{
                    "android.permission.WRITE_EXTERNAL_STORAGE",
                    "android.permission.READ_EXTERNAL_STORAGE",
                    "android.permission.READ_PHONE_STATE",
                    "ACCESS_NETWORK_STATE"
            },101);
        }
        initView();
        //启动+绑定服务
        initService();
        //点击列表播放音乐
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                musicBinder.play(position);

            }
        });
        //注册广播
        initRecevicer();




    }

    private void initRecevicer() {
        musicRecevicer = new MusicRecevicer();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.bawei.pre");
        intentFilter.addAction("com.bawei.play");
        intentFilter.addAction("com.bawei.next");
        intentFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);//来电广播
        intentFilter.addAction( ConnectivityManager.CONNECTIVITY_ACTION);//网络链接广播
        registerReceiver(musicRecevicer,intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(musicRecevicer);
        timer.cancel();
    }

    private void initService() {
        Intent intent = new Intent(this, MusicService.class);
        startService(intent);
        bindService(intent,serviceConnection, Service.BIND_AUTO_CREATE);
    }

    private void initView() {
        listView = findViewById(R.id.lv);
        imageView = findViewById(R.id.iv);
        relativeLayout = findViewById(R.id.rl);
        iv_next = findViewById(R.id.iv_next);
        iv_pre = findViewById(R.id.iv_pre);
        iv_paly = findViewById(R.id.iv_play);
        textView = findViewById(R.id.tv_name);
        songBeans =  SongsUtils.getSongs(this);
        songAdapter = new SongAdapter(songBeans,this);
        listView.setAdapter(songAdapter);

        iv_paly.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                musicBinder.pauseOrstart();
            }
        });
        iv_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                musicBinder.next();

            }
        });
        iv_pre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                musicBinder.pre();

            }
        });
        //点击下面条目，弹出窗体
        relativeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopupWindow popupWindow = new PopupWindow(MainActivity.this);
                popupWindow.setWidth(RelativeLayout.LayoutParams.MATCH_PARENT);
                popupWindow.setHeight(RelativeLayout.LayoutParams.MATCH_PARENT);
                View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.popup_windoe, null);
                final TextView textView = view.findViewById(R.id.tv_name);
                final ImageView imageView = view.findViewById(R.id.iv);
                 seekBar = view.findViewById(R.id.bar);
                 tv_duration= view.findViewById(R.id.tv_duration);
                 tv_current= view.findViewById(R.id.tv_current);
                view.findViewById(R.id.iv_pre).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        musicBinder.pre();
                        textView.setText(musicBinder.getName());
                        Glide.with(MainActivity.this)
                                .load(musicBinder.getImage())
                                .transform(new CircleCrop())
                                .into(imageView);
                    }
                });
                view.findViewById(R.id.iv_next).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        musicBinder.next();
                        textView.setText(musicBinder.getName());
                        Glide.with(MainActivity.this)
                                .load(musicBinder.getImage())
                                .transform(new CircleCrop())
                                .into(imageView);
                    }
                });
                seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                        if(fromUser){
                            musicBinder.seekTo(progress);
                        }
                    }

                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {

                    }

                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {

                    }
                });
                view.findViewById(R.id.iv_play).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        musicBinder.pauseOrstart();
                    }
                });
                textView.setText(musicBinder.getName());
                Glide.with(MainActivity.this)
                        .load(musicBinder.getImage())
                        .transform(new CircleCrop())
                        .into(imageView);

                popupWindow.setContentView(view);
                popupWindow.showAtLocation(v, Gravity.BOTTOM,0,0);




                initTimer();

            }
        });
    }

    private void initTimer() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                final long duration = musicBinder.getDuration();
                final long current = musicBinder.getCurrent();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        seekBar.setMax((int) duration);
                        seekBar.setProgress((int) current);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");
                        tv_current.setText(simpleDateFormat.format(current));
                        tv_duration.setText(simpleDateFormat.format(duration));
                    }
                });

            }
        },0,100);
    }


    class MusicRecevicer extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if("com.bawei.pre".equals(intent.getAction())){
                musicBinder.pre();

            }else  if("com.bawei.next".equals(intent.getAction())){
                musicBinder.next();

            }else  if("com.bawei.play".equals(intent.getAction())){
                musicBinder.pauseOrstart();
            }else  if("c".equals(intent.getAction())){
                textView.setText(musicBinder.getName()+"");
                Glide.with(MainActivity.this)
                        .load(musicBinder.getImage())
                        .transform(new CircleCrop())
                        .into(imageView);

            }else  if(TelephonyManager.ACTION_PHONE_STATE_CHANGED.equals(intent.getAction())){
                //
                TelephonyManager telManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); // 获取系统服务
                telManager.listen(new PhoneStateListener(){
                                      @Override
                                      public void onCallStateChanged(int state, String incomingNumber) {
                                          switch (state) {
                                              case TelephonyManager.CALL_STATE_IDLE: // 挂机状态
                                                  Log.d(TAG, "挂机状态 ");
                                                    musicBinder.start();
                                                  break;
                                              case TelephonyManager.CALL_STATE_OFFHOOK:	//通话状态
                                                  musicBinder.pause();
                                                  Log.d(TAG, "通话状态 ");
                                              case TelephonyManager.CALL_STATE_RINGING:	//响铃状态
                                                  musicBinder.pause();

                                                  Log.d(TAG, "响铃状态 ");
                                                  break;
                                              default:
                                                  break;
                                          }
                                      }
                                  },
                        PhoneStateListener.LISTEN_CALL_STATE);

            }else  if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())){//网络状态


                //获取连接服务 CONNECTIVITY_SERVICE
                ConnectivityManager connectivityManager = (ConnectivityManager) context

                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                //获取当前网络连接
                NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();

                if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
                    if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_WIFI)) {
                        //当前处于无线网络
                        musicBinder.start();

                    } else if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_MOBILE)) {
                        //当前处于移动网络
                        musicBinder.start();
                    }
                } else {
                    //无网络
                    musicBinder.pause();
                }




//                int netWorkState = NetUtils.getNetWorkState(context);
//                Toast.makeText(context, ""+netWorkState, Toast.LENGTH_SHORT).show();
//                if(musicBinder != null){
//                    if(netWorkState == NetUtils.NO_NET){//无网
//                        musicBinder.pause();
//                    }else{//播放
//                        musicBinder.start();
//                    }
//                }



            }
        }
    }
}
